import { useState, useEffect } from 'react'
import { PageContainer, ProFormCascader, ProForm } from '@ant-design/pro-components'
import { Alert, Tabs } from 'antd'
import { GetListFnc, GetAttrFnc } from '@/services/params'
import Tables from './components/Table'
import style from './index.less'


const Params = () => {
  const [options, setOptions] = useState([]) // 级联选择器
  const [btnDisabled, setBtnDisabled] = useState(true) // 添加参数 或者 属性 按钮
  const [activeName, setActiveName] = useState('many') // many=参数  only=属性
  const [cascaderValue, setCascaderValue] = useState('') // 级联选择器的值
  const [dataSource, setDataSource] = useState([]) // 表格数据
  const [catID, setCatID] = useState('') // catID的值
  

  // 获取table数据  
  const getTable = async (cascaderVal: string, activeNameVal: string) => {
    const res = await GetAttrFnc(parseInt(cascaderVal), {sel: activeNameVal})
    if(res.meta.status === 200 && res.data.length !== 0) {
      setDataSource(res.data)
      setBtnDisabled(false)
    }
  }

  const tabItems = [
    { key: 'many', label: '动态参数', children: <Tables getTable={getTable} catID={catID} dataSource={dataSource} activeName={activeName} cascaderValue={cascaderValue} btnDisabled={btnDisabled}/>},
    { key: 'only', label: '静态属性', children: <Tables getTable={getTable} catID={catID} dataSource={dataSource} activeName={activeName} cascaderValue={cascaderValue} btnDisabled={btnDisabled}/>}
  ]

  // 级联数据初始化
  const init = async () => {
    const res = await GetListFnc()
    if(res.meta.status === 200) setOptions(res.data)
  }
  useEffect(() => { init() }, [])

  

  // 级联选择器 获取table数据  
  const getTableData = async (value: any[]) => {
    if(value !== undefined) {
      setCascaderValue(value[value.length - 1])
      getTable(value[value.length - 1], activeName)
      setCatID(value[value.length - 1])
    } else { // 清除级联选择器
      setBtnDisabled(true)
      setDataSource([])
      setCascaderValue('')
      setCatID('')
    }
  }

  // tab切换 获取table数据  
  const tabChange = async(value: string) => {
    setActiveName(value)
    if(cascaderValue !== '') {
      getTable(cascaderValue, value)
    }
  }

  return (
    <>
     <PageContainer header={{title: '', breadcrumb: { items: [{ title: '商品管理' }, { title: '参数列表' }] }}}>
      <div className={style.paramsContent}>
        <Alert message="注意:只允许为第三级分类设置相关参数!" type="warning" showIcon />

        {/* 商品级联选择器 */}
        <div className={style.select}>
          <ProForm submitter={false}>
            <ProFormCascader width={200} onChange={getTableData} label="选择商品分类:" name="goods_cat" fieldProps={{options: options, fieldNames: {label: 'cat_name', value: 'cat_id', children: 'children'}}}/>
          </ProForm>
        </div>  

        {/* 选项卡 */}
        <Tabs items={tabItems} onChange={tabChange}/>
      </div>
     </PageContainer> 
    </>
  )
}

export default Params